﻿#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using HouseHoldBudget.App_GlobalResources;
using HouseHoldBudget.Core.Entities.Budgets;
using HouseHoldBudget.Core.Entities.Expenses;
using HouseHoldBudget.Core.Entities.User;
using HouseHoldBudget.Framework.Mvc.Controllers;
using HouseHoldBudget.Infrastructure;
using HouseHoldBudget.Models.Budgets;
using HouseHoldBudget.Models.Expenses;
using HouseHoldBudget.Models.User;
using HouseHoldBudget.Services.Budgets;
using HouseHoldBudget.Services.Expenses;
using HouseHoldBudget.Services.Incomes;
using HouseHoldBudget.Services.Users;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;

#endregion

namespace HouseHoldBudget.Controllers
{
    public class BudgetController : BudgetControllerBase
    {
        #region Readonly & Static Fields

        private readonly IBudgetCategoryService _budgetCategoryService;
        private readonly IBudgetService _budgetService;
        private readonly IFixedIncomesService _fixedIncomesService;
        private readonly IUserService _userService;
        private readonly IExpenseTypesService _expenseTypesService;
        private readonly IExpenseService _expenseService;


        #endregion

        #region Constructors

        public BudgetController(IBudgetService budgetService,
                                IBudgetCategoryService budgetCategoryService,
                                IFixedIncomesService fixedIncomesService,
                                IUserService userService,
                                IExpenseTypesService expenseTypesService,
                                IExpenseService expenseService)
        {
            _budgetService = budgetService;
            _budgetCategoryService = budgetCategoryService;
            _fixedIncomesService = fixedIncomesService;
            _userService = userService;
            _expenseTypesService = expenseTypesService;
            _expenseService = expenseService;
        }

        #endregion

        #region Edit & Create Budget

        #region Budget

        /// <summary>
        /// Manages my budgets.
        /// </summary>
        /// <returns></returns>
        public ActionResult ManageMyBudgets()
        {
            return View(new BudgetModel());
        }

        /// <summary>
        /// Gets my budgets.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public ActionResult SelectMyBudgets([DataSourceRequest] DataSourceRequest request)
        {
            return GetMyBudgetsAsJson(request);
        }

        /// <summary>
        /// Creates a budget.
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateBudget()
        {
            BudgetModel model = new BudgetModel
                                    {
                                        BudgetName = string.Empty,
                                        Id = Guid.Empty,
                                        BudgetOwner = CurrentBudgetUser.ToModel(),
                                        CreatedOn = DateTime.Now,
                                        BudgetTypesItems = new List<SelectListItem>()
                                          {
                                              new SelectListItem(){ Text = "Annuel", Value = "2"},
                                              new SelectListItem(){ Text = "Mensuel", Value = "1"}
                                          }
                                    };

            return View(model);
        }

        /// <summary>
        /// Saves the budget.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="continueEditing">if set to <c>true</c> [continue editing].</param>
        /// <returns></returns>
        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        [FormValueRequired("save", "save-continue")]
        public ActionResult CreateBudget(BudgetModel model, bool continueEditing)
        {
            if (ModelState.IsValid)
            {
                Budget budget = model.ToEntity();
                budget.Id = Guid.NewGuid();
                budget.BudgetOwnerId = CurrentBudgetUser.Id;
                budget.BudgetCreatedOn = DateTime.Now;

                _budgetService.InsertBudget(budget);

                return continueEditing ? RedirectToAction("EditBudget", new {budgetId = budget.Id}) : RedirectToAction("ManageMyBudgets");
            }

            return CreateBudget();
        }

        /// <summary>
        /// Edits the budget.
        /// </summary>
        /// <param name="budgetId">The budget id.</param>
        /// <returns></returns>
        public ActionResult EditBudget(Guid budgetId)
        {
            Budget budget = _budgetService.GetBudgetById(budgetId);
            
            //Authorized only if i'm budget owner
            if(budget.BudgetOwner.Id != CurrentBudgetUser.Id)
            {
                return AccessDeniedView();
            }

            FillViewData(budget);

            //Add budget types
            BudgetModel budgetModel = budget.ToModel();
            budgetModel.BudgetTypesItems = new List<SelectListItem>()
                                          {
                                              new SelectListItem(){ Text = "Annuel", Value = "2"},
                                              new SelectListItem(){ Text = "Mensuel", Value = "1"}
                                          };

            //Actors
            AddActorsToBudget(budgetModel, budget);

            //Categories
            AddCategoriesToBudget(budgetModel, budget);

            //Owner
            AddOwnerToBudget(budgetModel, budget);

            return View(budgetModel);
        }

        /// <summary>
        /// Edits the budget.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="continueEditing">if set to <c>true</c> [continue editing].</param>
        /// <returns></returns>
        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        [FormValueRequired("save", "save-continue")]
        public ActionResult EditBudget(BudgetModel model, bool continueEditing)
        {
            if (string.IsNullOrEmpty(model.BudgetName))
            {
                ModelState.AddModelError("", "Le nom du budget est obligatoire!");
            }

            if (ModelState.IsValid)
            {
                Budget budget = _budgetService.GetBudgetById(model.Id);
                if (budget.BudgetOwner.Id != CurrentBudgetUser.Id)
                {
                    return AccessDeniedView();
                }

                budget.BudgetDescription = model.BudgetDescription;
                budget.BudgetName = model.BudgetName;
                budget.BudgetTypeId = model.BudgetTypeId;
                budget.BudgetUpdatedOn = DateTime.Now;

                _budgetService.UpdateBudget(budget);

                return continueEditing ? RedirectToAction("EditBudget", new {budgetId = budget.Id}) : RedirectToAction("ManageMyBudgets");
            }

            return View(model);

        }

        /// <summary>
        /// Deletes the budget.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        [HttpPost]
        [FormValueRequired("delete-budget")]
        public ActionResult DeleteBudget(Guid id)
        {
            //TODO: check user permission

            _budgetService.DeleteBudget(id);
            return View("ManageMyBudgets");
        }

        /// <summary>
        /// Gets my budgets as json.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        [NonAction]
        private JsonResult GetMyBudgetsAsJson([DataSourceRequest] DataSourceRequest request)
        {
            var budgets = _budgetService.GetMyBudgets(CurrentBudgetUser.Id);
            return Json(budgets.Select(b => b.ToModel()).ToDataSourceResult(request, ModelState));
        }

        #endregion

        #region Budget Category

        /// <summary>
        /// Selects all budget categories.
        /// </summary>
        /// <param name="budgetId">The budget id.</param>
        /// <returns></returns>
        public ActionResult SelectAllBudgetCategories(Guid budgetId)
        {
            List<BudgetCategoryModel> list = GetAllBudgetCategories(budgetId);
            list.Insert(0, new BudgetCategoryModel
                               {
                                   Id = new Guid(),
                                   BudgetCategoryName = CustomResources.Common_NotDefined
                               });

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Returns all budget categories by budget id.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="budgetId">The budget id.</param>
        /// <returns></returns>
        public ActionResult SelectBudgetCategories([DataSourceRequest] DataSourceRequest request, Guid budgetId)
        {
            return SelectBudgetCategoryAsJSon(request, budgetId);
        }

        /// <summary>
        /// Inserts a budget category.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult InsertBudgetCategory([DataSourceRequest] DataSourceRequest request, BudgetCategoryModel model)
        {
            if (ModelState.IsValid)
            {
                //Create new cateory
                BudgetCategory category = model.ToEntity();
                category.Id = Guid.NewGuid();
                //Insert categor to model
                Budget budget = _budgetService.GetBudgetById(model.BudgetId);
                budget.BudgetCategories.Add(category);
                _budgetService.UpdateBudget(budget);

                //Update view data
                FillViewData(budget);

                //Return categories from budget
                model.Id = category.Id;
                return Json(new[] {model}.ToDataSourceResult(request, ModelState));
            }

            return RedirectToAction("SelectBudgetCategories");
        }

        /// <summary>
        /// Delete a budgets category.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="id">The id.</param>
        /// <param name="budgetId">The budget id.</param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteBudgetCategory([DataSourceRequest] DataSourceRequest request, Guid id, Guid budgetId)
        {
            //Remove category to budget
            BudgetCategory category = _budgetCategoryService.GetBudgetCategory(id);
            _budgetCategoryService.DeleteBudgetCategory(category);

            //Update view data
            Budget budget = _budgetService.GetBudgetById(budgetId);
            FillViewData(budget);

            //Return categories from budget
            return SelectBudgetCategoryAsJSon(request, budgetId);
        }

        /// <summary>
        /// Updates the budget category.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UpdateBudgetCategory([DataSourceRequest] DataSourceRequest request, BudgetCategoryModel model)
        {
            if (ModelState.IsValid)
            {
                //Get category and update it
                var category = _budgetCategoryService.GetBudgetCategory(model.Id);
                category = model.ToEntity(category);
                _budgetCategoryService.UpdateBudgetCategory(category);

                //Update view data
                Budget budget = _budgetService.GetBudgetById(model.BudgetId);
                FillViewData(budget);

                //Return categories from budget
                return SelectBudgetCategories(request, model.BudgetId);
            }

            return RedirectToAction("SelectBudgetCategories");
        }

        /// <summary>
        /// Selects the budget category as J son.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="budgetId">The budget id.</param>
        /// <returns></returns>
        [NonAction]
        private JsonResult SelectBudgetCategoryAsJSon([DataSourceRequest] DataSourceRequest request, Guid budgetId)
        {
            var budget = _budgetService.GetBudgetById(budgetId);
            return Json(budget.BudgetCategories.Select(p => p.ToModel()).ToDataSourceResult(request, ModelState));
        }

        /// <summary>
        /// Gets all budget categories.
        /// </summary>
        /// <param name="budgetId">The budget id.</param>
        /// <returns></returns>
        [NonAction]
        private List<BudgetCategoryModel> GetAllBudgetCategories(Guid budgetId)
        {
            var categories = _budgetService.GetBudgetById(budgetId).BudgetCategories;
            return categories.Select(p => p.ToModel()).ToList();
        }

        #endregion

        #region Budget Actors

        /// <summary>
        /// Selects the budget actors.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="budgetId">The budget id.</param>
        /// <returns></returns>
        public ActionResult SelectBudgetActors([DataSourceRequest] DataSourceRequest request, Guid budgetId)
        {
            return GetBudgetActorsAsJson(request, budgetId);
        }

        /// <summary>
        /// Inserts the budget fixed income.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult InsertBudgetActor([DataSourceRequest] DataSourceRequest request, BudgetUserModel model)
        {
            if (ModelState.IsValid)
            {
                //check if user is already define in the current budget
                BudgetUser user = _userService.GetUserById(model.UserId);
                Budget budget = _budgetService.GetBudgetById(model.BudgetId);
                if (budget.BudgetActors.Contains(user))
                {
                    ModelState.AddModelError("", "Cet utilisateur est déjà défini dans ce budget!");
                    return RedirectToAction("SelectBudgetActors");
                }
                
                //Add user to the budget
                budget.BudgetActors.Add(user);
                _budgetService.UpdateBudget(budget);

                FillViewData(budget);

                model.Id = user.Id;
                return Json(new[] { model }.ToDataSourceResult(request, ModelState));
            }

            return RedirectToAction("SelectBudgetActors");
        }

        /// <summary>
        /// Deletes the budget actor.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="id">The id.</param>
        /// <param name="budgetId">The budget id.</param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteBudgetActor([DataSourceRequest] DataSourceRequest request, Guid id, Guid budgetId)
        {
            if (ModelState.IsValid)
            {
                BudgetUser user = _userService.GetUserById(id);
                Budget budget = _budgetService.GetBudgetById(budgetId);
                budget.BudgetActors.Remove(user);
                _budgetService.UpdateBudget(budget);

                FillViewData(budget);

                return SelectBudgetActors(request, budgetId);
            }

            return RedirectToAction("SelectBudgetActors");
        }

        /// <summary>
        /// Gets the budget actors as json.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="budgetId">The budget id.</param>
        /// <returns></returns>
        [NonAction]
        private JsonResult GetBudgetActorsAsJson(DataSourceRequest request, Guid budgetId)
        {
            var actors = _budgetService.GetBudgetActors(budgetId);
            return Json(actors.Select(p =>
            {
                var m = p.ToModel();
                m.UserId = m.Id;
                m.BudgetId = budgetId;
                return m;
            }).ToDataSourceResult(request, ModelState));
        }

        #endregion

        #region Budget CategoryExpenseTypes

        /// <summary>
        /// Returns all budget categories by budget id.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="budgetId">The budget id.</param>
        /// <returns></returns>
        public ActionResult SelectBudgetCategoryExpenseTypes([DataSourceRequest] DataSourceRequest request, Guid budgetId)
        {
            var budget = _budgetService.GetBudgetById(budgetId);
            var model = GetBudgetCategoryExpenseTypesModel(budget);
            return Json(model.ToDataSourceResult(request));
        }

        /// <summary>
        /// Updates the budget category expense types.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UpdateBudgetCategoryExpenseTypes([DataSourceRequest] DataSourceRequest request, BudgetCategoryExpenseTypesModel model)
        {
            var budget = _budgetService.GetBudgetById(model.BudgetId);

            if (ModelState.IsValid)
            {
                
                bool removeCategoryMapping = model.BudgetCategory.BudgetCategoryName == CustomResources.Common_NotDefined;

                if (!removeCategoryMapping)
                {
                    var category = budget.BudgetCategories.SingleOrDefault(p => p.Id == model.BudgetCategory.Id);
                    var expType = _expenseTypesService.GetExpenseTypeById(model.ExpenseTypeId);

                    if (category != null && expType != null)
                    {
                        if (category.ExpenseTypes.Contains(expType))
                        {
                            category.ExpenseTypes.Remove(expType);

                            category.ExpenseTypes.Add(expType);
                        }
                        else
                        {
                            category.ExpenseTypes.Add(expType);
                        }

                        model.OriginalBudgetCategoryId = model.BudgetCategory.Id;

                        _budgetCategoryService.UpdateBudgetCategory(category);
                    }
                }
                else
                {
                    // remove mapping
                    var category = budget.BudgetCategories.SingleOrDefault(p => p.Id == model.OriginalBudgetCategoryId);
                    var expType = _expenseTypesService.GetExpenseTypeById(model.ExpenseTypeId);
                    if (category != null && expType != null)
                    {
                        if (category.ExpenseTypes.Contains(expType))
                        {
                            category.ExpenseTypes.Remove(expType);
                            _budgetCategoryService.UpdateBudgetCategory(category);
                        }
                    }
                }
            }

            return Json(model);
        }

        #endregion

        #endregion

        #region Show Budget Result

        /// <summary>
        /// Shows all budgets.
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowAllBudgets()
        {
            return View(new BudgetResultModel());
        }

        /// <summary>
        /// Selects all budgets.
        /// </summary>
        /// <returns></returns>
        public ActionResult SelectAllBudgets([DataSourceRequest] DataSourceRequest request)
        {
            return GetAllBudgetsAsJson(request);
        }

        /// <summary>
        /// Gets all budgets as json.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        [NonAction]
        private JsonResult GetAllBudgetsAsJson([DataSourceRequest] DataSourceRequest request)
        {
            var budgets = _budgetService.GetAllBudgets(CurrentBudgetUser.Id);
            return Json(budgets.Select(p=> PrepareBudgetResultModel(p, null, null)).ToDataSourceResult(request, ModelState));
        }

        /// <summary>
        /// Shows the budget.
        /// </summary>
        /// <param name="budgetId">The budget id.</param>
        /// <param name="month">The month period.</param>
        /// <param name="year">The annual period.</param>
        /// <returns></returns>
        public ActionResult ShowBudget(Guid budgetId, int? month, int? year)
        {
            Budget budget = _budgetService.GetBudgetById(budgetId);
            
            return View(PrepareBudgetResultModel(budget, year, month));
        }

        /// <summary>
        /// Shows the budget.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [HttpPost]
        [FormValueRequired("show-budget-period")]
        public ActionResult ShowBudget(BudgetResultModel model)
        {
            Budget budget = _budgetService.GetBudgetById(model.Id);

            return View(PrepareBudgetResultModel(budget, model.AnnualPeriod, model.MonthPeriod));
        }

        /// <summary>
        /// Selects all budget expenses.
        /// </summary>
        /// <param name="budgetId">The budget id.</param>
        /// <param name="month">The month period.</param>
        /// <param name="year">The annual period.</param>
        /// <returns></returns>
        public ActionResult SelectAllBudgetExpenses([DataSourceRequest] DataSourceRequest request, Guid budgetId, int month, int year)
        {
            var expenses = _expenseService.GetAllExpensesByBudgetId(budgetId, year, month);
            return Json(expenses.Select(PrepareExpenseModel).ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Selects all budget expenses for chart.
        /// </summary>
        /// <param name="budgetId">The budget id.</param>
        /// <param name="month">The month.</param>
        /// <param name="year">The year.</param>
        /// <returns></returns>
        public ActionResult SelectAllBudgetExpensesForChart(Guid budgetId, int month, int year)
        {
            Budget budget = _budgetService.GetBudgetById(budgetId);
            var expenses = _expenseService.GetAllExpensesByBudgetId(budgetId, year, month);
            var excat = (from budgetCategory in budget.BudgetCategories
                         let expenseAmount = budgetCategory.ExpenseTypes.Sum(expenseType => expenses.Where(p => p.ExpensesTypeId == expenseType.Id).Sum(p => p.ExpenseAmount))
                         select new CategoryExpenseModel()
                                    {
                                        CategoryName = budgetCategory.BudgetCategoryName, 
                                        CategoryExpenseAmount = expenseAmount,
                                        CategoryExpenseAppointedAmount = budgetCategory.RepartitionAmount
                                    }).ToList();
            return Json(excat);
        }

        /// <summary>
        /// Selects all budget expenses for grid.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="budgetId">The budget id.</param>
        /// <param name="month">The month.</param>
        /// <param name="year">The year.</param>
        /// <returns></returns>
        public ActionResult SelectAllBudgetExpensesForGrid([DataSourceRequest] DataSourceRequest request, Guid budgetId, int month, int year)
        {
            Budget budget = _budgetService.GetBudgetById(budgetId);
            var expenses = _expenseService.GetAllExpensesByBudgetId(budgetId, year, month);
            var excat = (from budgetCategory in budget.BudgetCategories
                         let expenseAmount = budgetCategory.ExpenseTypes.Sum(expenseType => expenses.Where(p => p.ExpensesTypeId == expenseType.Id).Sum(p => p.ExpenseAmount))
                         select new CategoryExpenseModel()
                         {
                             CategoryName = budgetCategory.BudgetCategoryName,
                             CategoryExpenseAmount = expenseAmount,
                             CategoryExpenseAppointedAmount = budgetCategory.RepartitionAmount
                         }).ToList();
            return Json(excat.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region Helpers

        /// <summary>
        /// Prepares the expense model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [NonAction]
        private ExpenseModel PrepareExpenseModel(Expense model)
        {
            ExpenseModel expense = model.ToModel();

            expense.ExpenseType = _expenseTypesService.GetExpenseTypeById(model.ExpensesTypeId.Value).ToModel();

            expense.UserFullName = model.BudgetUser.GetUserFullName();
            return expense;
        }

        /// <summary>
        /// Prepares the budget R esult model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="year">The year.</param>
        /// <param name="month">The month.</param>
        /// <returns></returns>
        [NonAction]
        private BudgetResultModel PrepareBudgetResultModel(Budget model, int? year, int? month)
        {
            BudgetResultModel budgetModel = model.ToModel2();

            AddActorsToBudget(budgetModel, model);
            AddCategoriesToBudget(budgetModel, model);
            AddOwnerToBudget(budgetModel, model);
            budgetModel.PrepareMonthPeriodItems();
            budgetModel.PrepareYearPeriodItems();
            budgetModel.MonthPeriod = month.HasValue ? month.Value : DateTime.Now.Month;
            budgetModel.AnnualPeriod = year.HasValue ? year.Value: DateTime.Now.Year;
            return budgetModel;
        }

        /// <summary>
        /// Adds the actors to budget.
        /// </summary>
        /// <param name="budgetModel">The budget model.</param>
        /// <param name="model">The model.</param>
        [NonAction]
        private void AddActorsToBudget(BudgetModel budgetModel, Budget model)
        {
            foreach (var actor in model.BudgetActors)
            {
                budgetModel.BudgetActors.Add(actor.ToModel());
            }
        }

        /// <summary>
        /// Adds the categories to budget.
        /// </summary>
        /// <param name="budgetModel">The budget model.</param>
        /// <param name="model">The model.</param>
        [NonAction]
        private void AddCategoriesToBudget(BudgetModel budgetModel, Budget model)
        {
            foreach (var item in model.BudgetCategories)
            {
                budgetModel.BudgetCategories.Add(item.ToModel());
            }
        }

        /// <summary>
        /// Adds the owner to budget.
        /// </summary>
        /// <param name="budgetModel">The budget model.</param>
        /// <param name="model">The model.</param>
        [NonAction]
        private void AddOwnerToBudget(BudgetModel budgetModel, Budget model)
        {
            budgetModel.BudgetOwner = model.BudgetOwner.ToModel();
        }

        /// <summary>
        /// Fills the users view data.
        /// </summary>
        /// <param name="budget">The budget.</param>
        [NonAction]
        private void FillViewData(Budget budget)
        {
            //Users list
            var users = _userService.GetAllUser(CurrentBudgetUser.Id, true);
            ViewData["allUsers"] = new List<BudgetUserModel>(users.Select(u =>
                                                                              {
                                                                                  var m = u.ToModel();
                                                                                  m.Id = u.Id;
                                                                                  m.UserId = m.Id;
                                                                                  m.BudgetId = budget.Id;
                                                                                  return m;
                                                                              }));

            if (users != null && users.FirstOrDefault() != null)
            {
                ViewData["defaultUserId"] = users.FirstOrDefault().Id;
            }
        }

        [NonAction]
        private IEnumerable<BudgetCategoryExpenseTypesModel> GetBudgetCategoryExpenseTypesModel(Budget model)
        {
            List<BudgetCategoryExpenseTypesModel> result = new List<BudgetCategoryExpenseTypesModel>();

            var expenseTypes = _expenseTypesService.GetAllExpenseTypes();

            foreach (var expenseType in expenseTypes)
            {
                BudgetCategoryExpenseTypesModel extType = new BudgetCategoryExpenseTypesModel()
                                                              {
                                                                  BudgetId = model.Id,
                                                                  Id = expenseType.Id,
                                                                  ExpenseTypeName = expenseType.ExpenseTypeName,
                                                                  ExpenseTypeId = expenseType.Id,
                                                              };
                
                foreach (BudgetCategory category in model.BudgetCategories)
                {
                    if(category.ExpenseTypes.Contains(expenseType))
                    {
                        extType.BudgetCategory.Id = category.Id;
                        extType.BudgetCategory.BudgetCategoryName = category.BudgetCategoryName;
                        extType.OriginalBudgetCategoryId = category.Id;
                    }
                }


                if (string.IsNullOrEmpty(extType.BudgetCategory.BudgetCategoryName))
                {
                    extType.BudgetCategory.Id = new Guid();
                    extType.BudgetCategory.BudgetCategoryName = CustomResources.Common_NotDefined;

                }

                result.Add(extType);
            }

            return result;
        }

        #endregion
    }
}